package middlewares

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		// 执行一些前置逻辑
		logx.Info("中间件前面的执行")
		// 生成中间件实现逻辑。，将 header 中的 User-Agent 信息存到 context 中
		val := request.Header.Get("User-Agent")
		request.Header.Set("User-Agent", fmt.Sprintf("通过中间件 UserAgentMiddleware 拿到的 User-Agent 为：%s", val))

		// 调用下一个中间件或处理函数
		next(writer, request)

		// 执行一些后置逻辑
		logx.Info("中间件后面的执行")
	}
}
